// src/main.ts
import { createApp, type App as VueApp } from "vue";
import App from "./App.vue";
import "./style.scss";
import "uno.css";
import { createDynamicRouter } from "./router"; // 添加这行导入
// 同步加载的核心CSS和图标
import zhCn from "element-plus/es/locale/lang/zh-cn";

// 主启动函数
async function setupApp() {
  // 1. 创建应用实例
  const app = createApp(App);
  // 2. 并行加载核心依赖
  const [pinia, routerModule] = await Promise.all([
    import("pinia").then((m) => m.createPinia()),
    import("./router").then((m) => m),
  ]);
  // 3. 必须先注册Pinia!!!
  app.use(pinia);
  // 4. 初始化store并并行加载关键数据
  const userStore = await import("./stores/modules/user").then((m) =>
    m.useUserStore()
  );
  await userStore.initUserInfo(); // 初始化用户信息，自动登录

  // 3. 并行加载其他核心依赖
  const [ElementPlus, router] = await Promise.all([
    import("element-plus"),
    createDynamicRouter({
      roles: userStore.roles,
      permissions: userStore.permissions,
    }),
  ]);
  // 5. 注册其他插件
  app.use(ElementPlus, {
    locale: zhCn, // 直接使用导入的zhCn对象
  });

  app.use(router);
  // 4. 延迟加载非关键功能
  Promise.all([loadIcons(app), loadStores(), loadDirectives(app)]).catch(
    console.error
  );

  app.mount("#app");
  removeLoading();
}

async function loadIcons(app: VueApp) {
  // 正确导入方式
  const icons = await import("@element-plus/icons-vue");
  
  // 注册所有图标
  for (const [key, component] of Object.entries(icons)) {
    if (key !== "default") { // 排除可能的default导出
      app.component(key, component);
    }
  }
}

async function loadStores() {
  const [menuStore, themeStore, appStore] = await Promise.all([
    import("./stores/menu"),
    import("./stores/theme"),
    import("./stores/app"),
  ]);

  await Promise.all([
    menuStore.useMenuStore().fetchMenuTree(),
    themeStore.useThemeStore().initTheme(),
    appStore.useAppStore().initApp(),
  ]);
}
// 延迟加载指令,全局加载状态管理
async function loadDirectives(app: VueApp) {
  const { vLoadingFinish } = await import("./directives/loading");
  app.directive("loading-finish", vLoadingFinish);
}
// 移除加载动画
function removeLoading() {
  const el = document.getElementById("app-loading");
  el?.style.setProperty("opacity", "0", "important");
  el?.addEventListener("transitionend", () => el.remove(), { once: true });
}

// 错误处理
function showError(error: Error) {
  const el = document.getElementById("app-loading");
  if (!el) return;

  el.innerHTML = `
    <div class="error-fallback">
      <p>加载失败: ${error.message}</p>
      <button onclick="location.reload()">重试</button>
    </div>
  `;
  el.style.opacity = "1";
}

// 启动应用
setupApp().catch((error) => {
  console.error("应用初始化失败:", error);
  showError(error);
});
